import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter_deer/database/tables.dart';
import 'package:flutter_deer/generated/res_upload_oil_entity.dart';
import 'package:flutter_deer/mvvm/base_net_provider.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/util/toast_utils.dart';

class FccProvider extends BaseNetProvider {
  Timer? _uploadTimer;
  bool _isUploadRunning = false;

  // 开启循环
  void startUploadOrderCycle() {
    if (_isUploadRunning) {
      return;
    }
    _isUploadRunning = true;
    _scheduleNextUpload(sec: 3);
  }

  // 停止循环
  void stopUploadOrderCycle() {
    _uploadTimer?.cancel();
    _isUploadRunning = false;
  }

  // 循环任务
  void _scheduleNextUpload({int sec = 40}) {
    _uploadTimer?.cancel();
    _uploadTimer = Timer(Duration(seconds: sec), () {
      // 如果是调试模式 不上传
      if (!kDebugMode) {
        _uploadOrderListCycle();
        _checkOrderStatusCycle();
      }
    });
  }

  // 循环上传油单
  void _uploadOrderListCycle() {
    final mList = AppOrderBean.queryUpLoadOrder();
    if (mList.isEmpty) {
      _scheduleNextUpload();
      return;
    }

    List<dynamic> params;
    try {
      params = mList.map((e) => e.toUpLoadJson()).toList();
    } catch (e, s) {
      print('构造上传参数失败: $e\n$s');
      _scheduleNextUpload();
      return;
    }

    asyncRequestNetwork<List<ResUploadOilEntity>>(
      Method.post,
      isShow: false,
      url: HttpApi.uploadOrder,
      params: {
        'uploadRequests': params,
      },
      onSuccess: (data) {
        AppOrderBean.updateIsSynced(data);
        print('循环上传油单成功');
        final int delaySeconds = mList.length == 10 ? 30 : 5;
        _scheduleNextUpload(sec: delaySeconds);
      },
      onError: (code, msg) {
        print('循环上传油单失败 code: $code, msg: $msg');
        _scheduleNextUpload();
      },
    );
  }

  // 循环检测是否已支付
  void _checkOrderStatusCycle() {
    final mList = AppOrderBean.queryUnPayOrder();
    if (mList.isEmpty) {
      print('....................循环检测是否已支付 无未支付订单');
      return;
    }

    asyncRequestNetwork<List<ResUploadOilEntity>>(
      Method.post,
      isShow: false,
      url: HttpApi.getOrderStatus,
      params: {
        'energyOrderIds': mList.map((e) => e.energyOrderId).toList(),
      },
      onSuccess: (data) {
        AppOrderBean.updateOrderStatus(data);
        // print('循环检测是否已支付成功 dataSize: ${data?.length}');
      },
      onError: (code, msg) {
        // print('循环检测是否已支付失败 code: $code, msg: $msg');
      },
    );
  }

  // 单次上传油单
  void uploadOrderListSingle(AppOrderBean bean) {
    if (bean.isSynced) {
      print('[mny=${bean.mny}] 循环上传油单 已上传过');
      return;
    }

    final List<dynamic> params = [bean.toUpLoadJson()];

    asyncRequestNetwork<List<ResUploadOilEntity>>(
      Method.post,
      isShow: false,
      url: HttpApi.uploadOrder,
      params: {
        'uploadRequests': params,
      },
      onSuccess: (data) {
        AppOrderBean.updateIsSynced(data);
        print('循环上传油单成功');
      },
      onError: (code, msg) {
        Toast.show(msg);
        print('循环上传油单失败');
      },
    );
  }

  @override
  void dispose() {
    stopUploadOrderCycle();
    super.dispose();
  }
}
